package com.ricky.constencrypt.plugin

import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import kotlin.math.min


object AESUtil {
    private const val ALGORITHM = "AES"
    private lateinit var secretKey: SecretKeySpec

    fun setSecretKey(secretKey: String) {
        val keyBytes = ByteArray(32)
        val temp = secretKey.toByteArray(charset("UTF-8"))
        System.arraycopy(temp, 0, keyBytes, 0, min(temp.size.toDouble(), keyBytes.size.toDouble()).toInt())
        this.secretKey = SecretKeySpec(keyBytes, ALGORITHM)
    }

    fun encrypt(data: String): String {
        val cipher = Cipher.getInstance(ALGORITHM)
        cipher.init(Cipher.ENCRYPT_MODE, secretKey)
        val encryptedBytes = cipher.doFinal(data.toByteArray(charset("UTF-8")))
        return Base64.getEncoder().encodeToString(encryptedBytes)
    }

    fun decrypt(encryptedData: String?): String {
        val cipher = Cipher.getInstance(ALGORITHM)
        cipher.init(Cipher.DECRYPT_MODE, secretKey)
        val decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData))
        return String(decryptedBytes, charset("UTF-8"))
    }
}